//
//  HBShakeResultCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/12/10.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBShakeResultCtrl.h"
#import "HBShakeResultHeaderCell.h"
#import "HBShakeResultJXCell.h"
#import "HBShakeResultCountCell.h"
#import "HBShakeResultFriendHeaderCell.h"
#import "HBShakeResultFriendListCell.h"
#import "HBInvestCtrl.h"
#import "HBMyRedPacketListCtrl.h"
#import "CustomerShareView.h"
#import "UMSocialQQHandler.h"
#import "UMSocial.h"
#import "HBGetRedManager.h"
#import "MJRefresh.h"
#import "HBGetInviteUserRedItemInfo.h"
#import "HBInvestManager.h"
#import "HBAddBankCtrl.h"
#import "HBGetRedSharingUrlInfo.h"
#import "HBGetRedSharingUrlParam.h"
#import "HBGetRedSharingUrlParser.h"
#import "HBLoginManager.h"

@interface HBShakeResultCtrl ()
<
UITableViewDataSource,
UITableViewDelegate
>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) HBGetRedSharingUrlInfo *shareinfo;

@end


@implementation HBShakeResultCtrl

#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
   
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if ([HBGetRedManager sharedHBGetRedManager].userShakeRedInfo)
    {
        [self.tableView reloadData];
    }
}

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"摇金桔";
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:_tableView];
    INIT_TABLE(_tableView);
    [self showDoneWithTitle:@"分享"];
    
    __weak UITableView *tableView = self.tableView;
//    __weak typeof(self) weakSelf = self;
    
    // 下拉刷新
    tableView.mj_header = [HBOrangeHeader headerWithRefreshingBlock:^{
        
        [HBGetRedManager sharedHBGetRedManager].pageNum = 1;
        [HBGetRedManager requestToGetUserShakeRedWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
            if (isSuccess)
            {
                [tableView reloadData];
            }
            
        }];
        [HBGetRedManager requestToGetInviteUserRedWithResult:^(BOOL isSuccess, NSString *msg, NSError *error, BOOL isEmpty) {
            [tableView.mj_header endRefreshing];
            if (isSuccess)
            {
                [tableView reloadData];
            }
        }];
        
        if (tableView.mj_footer)
        {
            [tableView.mj_footer resetNoMoreData];
        }
        
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if ([HBGetRedManager sharedHBGetRedManager].inviteUserRedInfo.dataAry.count>0)
        {
            [HBGetRedManager sharedHBGetRedManager].pageNum++;
            [HBGetRedManager requestToGetInviteUserRedWithResult:^(BOOL isSuccess, NSString *msg, NSError *error, BOOL isEmpty) {
                [tableView.mj_footer endRefreshing];
                if (isSuccess&&!isEmpty)
                {
                    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                else
                {
                    if (isSuccess&&isEmpty)
                    {
                        [tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
            }];
        }
        else
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 结束刷新
                [tableView.mj_footer endRefreshing];
            });
        }
        
    }];
    
//    [self.tableView.mj_header beginRefreshing];
    
    [HBGetRedManager sharedHBGetRedManager].pageNum = 1;
    [HBGetRedManager requestToGetUserShakeRedWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
        if (isSuccess)
        {
            [tableView reloadData];
        }
        
    }];
    [HBGetRedManager requestToGetInviteUserRedWithResult:^(BOOL isSuccess, NSString *msg, NSError *error, BOOL isEmpty) {
        [tableView.mj_header endRefreshing];
        if (isSuccess)
        {
            [tableView reloadData];
        }
    }];
    
}

- (void)doBack
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)doDone
{
    [super doDone];
    [self requestToGetSharInfo];
}

-(void)showshare{
    [[[CustomerShareView sharedCustomerShareView]initWithTitle:@"分享到" cancelButtonTitle:@"取消分享" cancelButtonAction:nil otherButtonAction:^(NSInteger index, CustomerShareView * _Nullable shareView) {
        switch (index) {
            case CustomerShareType_QQ:
                [self sharetoQQfirend];
                break;
            case CustomerShareType_QQZone:
                [self sharetoQQfamily];
                break;
            case CustomerShareType_Weixin:
                [self sharetowechat];
                break;
            case CustomerShareType_QQWeixinTimeLine:
                [self sharetowechatFamily];
                break;
            default:
                break;
        }
        [shareView removeFromSuperview];
    }]showInView];
}

#pragma mark - private

- (NSString *)getCellIdentifierWithIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"";
    if (indexPath.section==0)
    {
        cellIdentifier = NSStringFromClass([HBShakeResultHeaderCell class]);
    }
    else if (indexPath.section==1)
    {
        cellIdentifier = NSStringFromClass([HBShakeResultJXCell class]);
    }
    else if (indexPath.section==2)
    {
        cellIdentifier = NSStringFromClass([HBShakeResultCountCell class]);
    }
    else if (indexPath.section==3)
    {
        cellIdentifier = NSStringFromClass([HBShakeResultFriendHeaderCell class]);
    }
    else
    {
        cellIdentifier = NSStringFromClass([HBShakeResultFriendListCell class]);
    }
    return cellIdentifier;
}

- (void)reloadDataWithUITableViewCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        [self uploadHBShakeResultHeaderCell:(HBShakeResultHeaderCell *)cell atIndexPath:indexPath];
    }
    else if (indexPath.section==1)
    {
        [self uploadHBShakeResultJXCell:(HBShakeResultJXCell *)cell atIndexPath:indexPath];
    }
    else if (indexPath.section==2)
    {
        [self uploadHBShakeResultCountCell:(HBShakeResultCountCell *)cell atIndexPath:indexPath];
    }
    else if (indexPath.section==3)
    {
        [self uploadHBShakeResultFriendHeaderCell:(HBShakeResultFriendHeaderCell *)cell atIndexPath:indexPath];
    }
    else
    {
        [self uploadHBShakeResultFriendListCell:(HBShakeResultFriendListCell *)cell atIndexPath:indexPath];
    }
}

- (CGFloat)getCellHeightWithIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    if (indexPath.section==0)
    {
        height = Height_HBShakeResultHeaderCell;
    }
    else if (indexPath.section==1)
    {
        height = Height_HBShakeResultJXCell;
    }
    else if (indexPath.section==2)
    {
        height = Height_HBShakeResultCountCell;
    }
    else if (indexPath.section==3)
    {
        height = Height_HBShakeResultFriendHeaderCell;
    }
    else
    {
        height = Height_HBShakeResultFriendListCell;
    }
    return height;

}

- (void)uploadHBShakeResultHeaderCell:(HBShakeResultHeaderCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.ActionClickToBuy = ^(){
        
//        [CustomLoadingView showHudToView:nil];
        [CustomLoadingView showHudToView:self.view];
        [HBInvestManager requestToGetUserInvestLimitWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
//            [CustomLoadingView hideHudForView:nil];
            [CustomLoadingView hideHudForView:self.view];
            if (isSuccess)
            {
//                HBInvestCtrl *investCtrl = [[HBInvestCtrl alloc]init];
//                [self.navigationController pushViewController:investCtrl animated:YES];
                
                if ([[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.bindCardStatus integerValue])
                {
                    HBInvestCtrl *investCtrl = [[HBInvestCtrl alloc]init];
                    [self.navigationController pushViewController:investCtrl animated:YES];
                }
                else
                {
                    HBAddBankCtrl *checkCtrl = [[HBAddBankCtrl alloc]init];
                    checkCtrl.viewpageJumpingFrom = isFromInvestView;
                    checkCtrl.isRealName = [[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.identityStatus integerValue];
                    //                checkCtrl.investMoney = self.moneyTF.text;
                    //                checkCtrl.userInvestInfo = userInvestInfo;
                    [self.navigationController pushViewController:checkCtrl animated:YES];
                }
            }
            else
            {
                DISSMISS_ERR(error?[error description]:msg);
            }
        }];
        
//        [self.navigationController pushViewController:[[HBInvestCtrl alloc]init] animated:YES];
    };

    cell.msgLable.text = [HBGetRedManager sharedHBGetRedManager].userShakeRedInfo.redComment;
    if ((int)([[HBGetRedManager sharedHBGetRedManager].userShakeRedInfo.redRate floatValue]*10000)%10)
    {
        cell.rateLable.text = [NSString stringWithFormat:@"+%.2f%%",(int)([[HBGetRedManager sharedHBGetRedManager].userShakeRedInfo.redRate floatValue]*10000)/100.0];
    }
    else
    {
        cell.rateLable.text = [NSString stringWithFormat:@"+%.1f%%",(int)([[HBGetRedManager sharedHBGetRedManager].userShakeRedInfo.redRate floatValue]*10000)/100.0];
    }
    
}

- (void)uploadHBShakeResultJXCell:(HBShakeResultJXCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)uploadHBShakeResultCountCell:(HBShakeResultCountCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.countLable.text = [HBGetRedManager sharedHBGetRedManager].userShakeRedInfo.shakeTimes;
}

- (void)uploadHBShakeResultFriendHeaderCell:(HBShakeResultFriendHeaderCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)uploadHBShakeResultFriendListCell:(HBShakeResultFriendListCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    if ([HBGetRedManager sharedHBGetRedManager].inviteUserRedInfo.dataAry.count>0)
    {
        HBGetInviteUserRedItemInfo *itemInfo = [HBGetRedManager sharedHBGetRedManager].inviteUserRedInfo.dataAry[indexPath.row];
        cell.titleLable.text = itemInfo.username;
        cell.rateLable.text = [NSString stringWithFormat:@"+%.2f%%",(int)([itemInfo.redRate floatValue]*10000)/100.0];
        cell.titlePlace.hidden = YES;
        cell.ratePlace.hidden = YES;
    }
    else
    {
        cell.titleLable.text = @"";
        cell.rateLable.text = @"";
        cell.titlePlace.hidden = NO;
        cell.ratePlace.hidden = NO;
    }
    
}



#pragma mark - active



#pragma mark - delegate&datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    return 5;
    if (([HBGetRedManager sharedHBGetRedManager].userShakeRedInfo.redRate)&&([HBGetRedManager sharedHBGetRedManager].inviteUserRedInfo.dataAry.count>0))
    {
        return 5;
    }
    else if([HBGetRedManager sharedHBGetRedManager].userShakeRedInfo.redRate)
    {
        return 5;
    }
    else
    {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section<4)
    {
        return 1;
    }
    else
    {
        return [HBGetRedManager sharedHBGetRedManager].inviteUserRedInfo.dataAry.count>0?[HBGetRedManager sharedHBGetRedManager].inviteUserRedInfo.dataAry.count:1;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self getCellIdentifierWithIndexPath:indexPath];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (indexPath.section==0)
    {
        if (!cell)
        {
            cell = [[HBShakeResultHeaderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
    }
    else if (indexPath.section==1)
    {
        if (!cell)
        {
            cell = [[HBShakeResultJXCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
    }
    else if (indexPath.section==2)
    {
        if (!cell)
        {
            cell = [[HBShakeResultCountCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
    }
    else if (indexPath.section==3)
    {
        if (!cell)
        {
            cell = [[HBShakeResultFriendHeaderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
    }
    else
    {
        if (!cell)
        {
            cell = [[HBShakeResultFriendListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
    }
    
    [self reloadDataWithUITableViewCell:cell atIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==[self.tableView numberOfSections]-1)
    {
        return 1/[UIScreen mainScreen].scale;
    }
    else
    {
        return 0;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section==[self.tableView numberOfSections]-1)
    {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/[UIScreen mainScreen].scale)];
        view.backgroundColor = [UIColor clearColor];
        return view;
    }
    else
    {
        return 0;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self getCellHeightWithIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==1)
    {
        HBMyRedPacketListCtrl *redCtrl = [[HBMyRedPacketListCtrl alloc]init];
        [self.navigationController pushViewController:redCtrl animated:YES];
    }
    
    
}

#pragma mark - net

- (void)requestToGetSharInfo
{
        [CustomLoadingView showHudToView:self.view];
        HBGetRedSharingUrlParam *param = [[HBGetRedSharingUrlParam alloc]init];
        HBGetRedSharingUrlParser *parser = [[HBGetRedSharingUrlParser alloc]init];
        [NetCenter getDataFromURL:Method_getRedSharingUrl params:param parser:parser result:^(ParserResult *myResult) {
            [CustomLoadingView hideHudForView:self.view];
            if (myResult.code==0)
            {
                HBGetRedSharingUrlInfo *info = (HBGetRedSharingUrlInfo *)myResult.result;
                self.shareinfo = info;
                [self showshare];
            }
            else
            {
                DISSMISS_ERR(myResult.message);
            }
    
        } failure:^(NSError *error) {
            [CustomLoadingView hideHudForView:self.view];
            DISSMISS_ERR([error description]);
        }];
    
}


#pragma mark - share
-(void)sharetowechat{
    //NSString *token = [LCLoginManager sharedLCLoginManager].currentUserInfo.token;
    UIImage *test = [UIImage imageNamed:@"share_image"];
    UMSocialUrlResource *source = [[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:@"http://www.yooyoo360.com/photo/2009-1-1/20090112122308970.jpg"];
    [UMSocialData defaultData].extConfig.wechatSessionData.title = self.shareinfo.redShareTitle;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = [NSString stringWithFormat:@"%@?uid=%@",self.shareinfo.redShareUrl,[HBLoginManager sharedHBLoginManager].currentUserInfo.uid];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:self.shareinfo.redShareDesc image:nil location:nil urlResource:source presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}


-(void)sharetowechatFamily{
    //NSString *token = [LCLoginManager sharedLCLoginManager].currentUserInfo.token;
    UIImage *test = [UIImage imageNamed:@"share_image"];
    UMSocialUrlResource *source = [[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:self.shareinfo.redShareImg];
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = self.shareinfo.redShareTitle;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url =  [NSString stringWithFormat:@"%@?uid=%@",self.shareinfo.redShareUrl,[HBLoginManager sharedHBLoginManager].currentUserInfo.uid];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:self.shareinfo.redShareDesc image:test location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}


-(void)sharetoQQfirend{
    //NSString *token = [LCLoginManager sharedLCLoginManager].currentUserInfo.token;
    //UIImage *test = [UIImage imageNamed:@"share_image"];
    UMSocialUrlResource *source = [[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:self.shareinfo.redShareImg];
    if ([QQApiInterface isQQInstalled]) {
        [UMSocialData defaultData].extConfig.qqData.title = self.shareinfo.redShareTitle;
        [UMSocialData defaultData].extConfig.qqData.url = [NSString stringWithFormat:@"%@?uid=%@",self.shareinfo.redShareUrl,[HBLoginManager sharedHBLoginManager].currentUserInfo.uid];
        [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:self.shareinfo.redShareDesc image:source location:nil urlResource:source presentedController:self completion:^(UMSocialResponseEntity *response){
            if (response.responseCode == UMSResponseCodeSuccess) {
                NSLog(@"分享成功！");
            }
        }];
    }else{
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有安装手机QQ" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
    }
}


-(void)sharetoQQfamily{
    //NSString *token = [LCLoginManager sharedLCLoginManager].currentUserInfo.token;
    //UIImage *test = [UIImage imageNamed:@"ABC"];
    UMSocialUrlResource *source = [[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:self.shareinfo.redShareImg];
    if ([QQApiInterface isQQInstalled]) {
        [UMSocialData defaultData].extConfig.qzoneData.url = [NSString stringWithFormat:@"%@?uid=%@",self.shareinfo.redShareUrl,[HBLoginManager sharedHBLoginManager].currentUserInfo.uid];
        [UMSocialData defaultData].extConfig.qzoneData.title = self.shareinfo.redShareTitle;
        [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQzone] content:self.shareinfo.redShareDesc image:source location:nil urlResource:source presentedController:self completion:^(UMSocialResponseEntity *response){
            if (response.responseCode == UMSResponseCodeSuccess) {
                NSLog(@"分享成功！");
            }
        }];
    }else{
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有安装手机QQ" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
    }
}


@end
